package com.sunchangming.stmdb;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;

/**
 * Page分4种：DBMeta、BtreeMeta、NonLeafPage、LeafPage。
 * @author cm
 *
 */
public abstract class Page {
	/**
	 * 所有的页面大小应该是一样的，故而这是一个静态变量，而不是成员变量。
	 */
	final static int pagesize=4096;
	protected byte[] data=new byte[pagesize];	
	
	static final byte T_DBMeta=1;
	static final byte T_BtreeMeta=2;
	static final byte T_NonLeaf=3;
	static final byte T_Leaf=4;
	
	final long getPageNumber(){
		return this.pageno;
	}
	
	static Page createByType(int type,byte[] data,long pageno){
		switch(type){
		case T_DBMeta:
			return new PageManager.DBMeta(data,pageno);
		case T_BtreeMeta:
			return new BtreeMeta(data,pageno);
		case T_NonLeaf:
			return new NonLeafPage(data,pageno);
		case T_Leaf:
			return new LeafPage(data,pageno);
		default:
			throw new RuntimeException("wrong page type"+type);
		}
	}
	private final long pageno;
	public Page(byte[] data,long pageno){
		this.data=data;
		this.pageno=pageno;
	}
	
	CodedOutputStream getOutputStream(){
		return CodedOutputStream.newInstance(data);
	}
	
	CodedInputStream getInputStream(){
		return CodedInputStream.newInstance(data);
	}
	
	private boolean isDirty=false;
	
	protected boolean isDirty() {
		return isDirty;
	}
	
	protected Page setDirty() {
		this.isDirty=true;
		return this;
	}
	
	abstract void onMarshal() throws java.io.IOException;
}
